# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

root=TreeNode(3)
root.left=TreeNode(9)
root.right=TreeNode(20)
root.right.left=TreeNode(15)
root.right.right=TreeNode(7)

def levelOrder(root):
    #广度优先遍历来求解
    res=[]  #用于存放结果的矩阵
    #创建一个队列
    queueList=[]
    #先将根节点入队
    queueList.append(root)

    while len(queueList)>0:
        queueListLen=len(queueList)
        i=0
        res_i=[]
        while i<queueListLen:
            top=queueList.pop(0)
            res_i.append(top.val)
            if top.left!=None:
                queueList.append(top.left)
            if top.right!=None:
                queueList.append(top.right)
            i+=1
        res.append(res_i)
    print(res[::-1])
levelOrder(root)